package com.zyd.shiro.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyd.shiro.business.entity.Assets;
import com.zyd.shiro.business.enums.AssetsType;
import com.zyd.shiro.business.enums.PurWay;
import com.zyd.shiro.business.service.PakAssetsService;
import com.zyd.shiro.business.vo.AssetsConditionVO;
import com.zyd.shiro.business.vo.UserConditionVO;
import com.zyd.shiro.framework.object.BaseConditionVO;
import com.zyd.shiro.persistence.beans.*;
import com.zyd.shiro.persistence.mapper.*;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class PakAssetsServiceImpl implements PakAssetsService {

    @Autowired
    private PakAssetsMapper pakAssetsMapper;

    @Autowired
    private PakDistributeLineMapper pakDistributeLineMapper;

    @Autowired
    private PakWithdrawalLineMapper pakWithdrawalLineMapper;

    @Autowired
    private PakRepairLineMapper pakRepairLineMapper;

    @Autowired
    private PakScrappedLineMapper pakScrappedLineMapper;

    @Autowired
    private PakBorrowLineMapper pakBorrowLineMapper;

    @Autowired
    private PakRestoreLineMapper pakRestoreLineMapper;

    @Autowired
    private PakMigrateLineMapper pakMigrateLineMapper;

    @Autowired
    private PakTransferLineMapper pakTransferLineMapper;

    @Autowired
    private PakInventoryLineMapper pakInventoryLineMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysOrgMapper sysOrgMapper;

    @Autowired
    private PakLocationMapper pakLocationMapper;

    @Autowired
    private PakAssetsClassMapper pakAssetsClassMapper;

    @Autowired
    private PakRequisitionLineMapper pakRequisitionLineMapper;

    @Override
    public Assets insert(Assets assets) {
        Assert.notNull(assets, "对象不可为空！");
        assets.getPakAssets().setUnicode("AS"+System.currentTimeMillis());

        assets.getPakAssets().setUpdateTime(new Date());
        assets.getPakAssets().setCreateTime(new Date());
        pakAssetsMapper.insertSelective(assets.getPakAssets());
        return assets;
    }

    @Override
    public void insertList(List<Assets> assetss) {
            for(Assets assets:assetss){
                assets.getPakAssets().setUnicode("AS"+System.currentTimeMillis());
                assets.getPakAssets().setUpdateTime(new Date());
                assets.getPakAssets().setCreateTime(new Date());
                pakAssetsMapper.insertSelective(assets.getPakAssets());
           }
    }


    /**
     * 根据主键字段进行删除，方法参数必须包含完整的主键属性
     *
     * @param primaryKey
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByPrimaryKey(Long primaryKey) {
        return pakAssetsMapper.deleteByPrimaryKey(primaryKey) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(Assets assets) {
        Assert.notNull(assets, "对象不可为空！");
        assets.setUpdateTime(new Date());
        return pakAssetsMapper.updateByPrimaryKey(assets.getPakAssets()) > 0;
    }

    @Override
    public boolean updateSelective(Assets assets) {
        Assert.notNull(assets, "对象不可为空！");
        assets.setUpdateTime(new Date());
        return pakAssetsMapper.updateByPrimaryKeySelective(assets.getPakAssets()) > 0;
    }

    /**
     * 根据主键字段进行查询，方法参数必须包含完整的主键属性，查询条件使用等号
     *
     * @param primaryKey
     * @return
     */

    @Override
    public Assets getByPrimaryKey(Long primaryKey) {
        PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(primaryKey);
        return null == pakAssets ? null : new Assets(pakAssets);
    }


    /**
     * 根据实体中的属性进行查询，只能有一个返回值，有多个结果时抛出异常，查询条件使用等号
     *
     * @param
     * @return
     */
    @Override
    public Assets getOneByEntity(Assets test) {
        Assert.notNull(test, "对象不可为空！");
        PakAssets pakAssets = pakAssetsMapper.selectOne(test.getPakAssets());
        return null == pakAssets ? null : new Assets(pakAssets);
    }

    @Override
    public List<Assets> listAll() {
        List<PakAssets> pakAssetss = pakAssetsMapper.selectAll();
        if (CollectionUtils.isEmpty(pakAssetss)) {
            return null;
        }
        List<Assets> assetss = new ArrayList<>();
        for (PakAssets pakAssets : pakAssetss) {

            assetss.add(new Assets(pakAssets));
        }
        return assetss;
    }

    @Override
    public List<Assets> listByEntity(Assets entity) {
        return null;
    }


    /**
     * 分页查询
     *
     * @param vo
     * @return
     */
    @Override
    public PageInfo<Assets> findPageBreakByCondition(AssetsConditionVO vo) {
        PageHelper.startPage(vo.getPageNumber(), vo.getPageSize());
        List<PakAssets> pakAssetss = pakAssetsMapper.findPageBreakByCondition(vo);
        if (CollectionUtils.isEmpty(pakAssetss)) {
            return null;
        }
        List<Assets> assetss = new ArrayList<>();
        for (PakAssets pakAssets : pakAssetss) {

            assetss.add(new Assets(pakAssets));
        }
        PageInfo bean = new PageInfo<PakAssets>(pakAssetss);
        bean.setList(assetss);
        return bean;
    }

    @Override
    public void increase(PakAssets pakAssets) {
        pakAssets.setUnicode("AS"+System.currentTimeMillis());
        pakAssets.setCreateTime(new Date());
        pakAssets.setUpdateTime(new Date());
        pakAssetsMapper.insert(pakAssets);
    }

    @Override
    public void increase(PakPurchaseLine purchaseLine, PakPurchase pakPurchase) {
        for(int i = 0;i < purchaseLine.getNumber(); i++){
            PakAssets assets = new PakAssets();
            assets.setUnicode("AS"+System.currentTimeMillis());
            assets.setCategories(purchaseLine.getCategories());
            assets.setCategories(purchaseLine.getCategories());
            assets.setName(purchaseLine.getName());
            assets.setAmt(purchaseLine.getAmt());
            assets.setBrand(purchaseLine.getBrand());
            assets.setSpecificationModel(purchaseLine.getSpecificationModel());
            assets.setUnit(purchaseLine.getUnit());
            assets.setLocation(pakPurchase.getLocation());
            assets.setStatus(0);
            assets.setStockTime(pakPurchase.getApplyTime());
            assets.setWareTime(new Date());
            assets.setStockWay(pakPurchase.getWay());
            assets.setDept(pakPurchase.getDept());
            assets.setOrg(pakPurchase.getOrg());
            increase(assets);
        }

    }

    @Override
    public void distribute(PakDistribute pakDistribute) {
        List<PakDistributeLine> distributeLines = pakDistributeLineMapper.findByDistribute(pakDistribute.getId());
        for(PakDistributeLine distributeLine:distributeLines){
            PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(distributeLine.getAssets());
            pakAssets.setUser(pakDistribute.getUser());
            pakAssets.setDept(pakDistribute.getDept());
            pakAssets.setOrg(pakDistribute.getOrg());
            pakAssets.setStatus(AssetsType.DISTR.getCode());
            pakAssetsMapper.updateByPrimaryKeySelective(pakAssets);
        }
    }

    @Override
    public void receive(PakDistribute pakDistribute) {
        List<PakDistributeLine> distributeLines = pakDistributeLineMapper.findByDistribute(pakDistribute.getId());
        for(PakDistributeLine distributeLine:distributeLines){
            PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(distributeLine.getAssets());
            pakAssets.setStatus(AssetsType.USE.getCode());
            pakAssetsMapper.updateByPrimaryKeySelective(pakAssets);
        }
    }

    @Override
    public void withdrawal(PakWithdrawal pakWithdrawal) {
        List<PakWithdrawalLine> pakWithdrawalLines = pakWithdrawalLineMapper.findByWithdrawal(pakWithdrawal.getId());
        for(PakWithdrawalLine pakWithdrawalLine:pakWithdrawalLines){
            PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(pakWithdrawalLine.getAssets());
            pakAssets.setUser(null);
            pakAssets.setStatus(AssetsType.IDLE.getCode());
            pakAssetsMapper.updateByPrimaryKeySelective(pakAssets);
        }
    }

    @Override
    public void repair(PakRepair pakRepair) {
        List<PakRepairLine> pakRepairLines = pakRepairLineMapper.findByRepair(pakRepair.getId());
        for(PakRepairLine pakRepairLine:pakRepairLines){
            PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(pakRepairLine.getAssets());
            pakAssets.setStatus(AssetsType.REPAIR.getCode());
            pakAssetsMapper.updateByPrimaryKeySelective(pakAssets);
        }
    }

    @Override
    public void scrapped(PakScrapped pakScrapped) {
        List<PakScrappedLine> pakScrappedLines = pakScrappedLineMapper.findByScrapped(pakScrapped.getId());
        for(PakScrappedLine pakScrappedLine:pakScrappedLines){
            PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(pakScrappedLine.getAssets());
            pakAssets.setStatus(AssetsType.SCRAP.getCode());
            pakAssetsMapper.updateByPrimaryKeySelective(pakAssets);
        }
    }

    @Override
    public PageInfo<Assets> listUser(AssetsConditionVO assetsConditionVO) {
        PageHelper.startPage(assetsConditionVO.getPageNumber(), assetsConditionVO.getPageSize());
        List<PakAssets> pakAssetss = pakAssetsMapper.listUser(assetsConditionVO);
        if (CollectionUtils.isEmpty(pakAssetss)) {
            return null;
        }
        List<Assets> assetss = new ArrayList<>();
        for (PakAssets pakAssets : pakAssetss) {
            assetss.add(new Assets(pakAssets));
        }
        PageInfo bean = new PageInfo<PakAssets>(pakAssetss);
        bean.setList(assetss);
        return bean;
    }

    @Override
    public void brrow(PakBorrow pakBorrow) {
        List<PakBorrowLine> pakBorrowLines = pakBorrowLineMapper.findByBorrow(pakBorrow.getId());
        for(PakBorrowLine pakBorrowLine:pakBorrowLines){
            PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(pakBorrowLine.getAssets());
            pakAssets.setStatus(AssetsType.BORROW.getCode());
            pakAssetsMapper.updateByPrimaryKeySelective(pakAssets);
        }
    }

    @Override
    public void restore(PakRestore pakRestore) {
        List<PakRestoreLine> pakRestoreLines = pakRestoreLineMapper.findByRestore(pakRestore.getId());
        for(PakRestoreLine pakRestoreLine:pakRestoreLines){
            PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(pakRestoreLine.getAssets());
            PakBorrowLine line = pakBorrowLineMapper.findByAssetsBorrow(pakRestoreLine.getAssets());
            line.setBostatus(0);
            pakBorrowLineMapper.updateByPrimaryKeySelective(line);
            pakAssets.setStatus(AssetsType.IDLE.getCode());
            pakAssetsMapper.updateByPrimaryKeySelective(pakAssets);
        }
    }

    @Override
    public void migrate(PakMigrate pakMigrate) {
        List<PakMigrateLine> pakMigrateLines = pakMigrateLineMapper.findByMigrate(pakMigrate.getId());
        for(PakMigrateLine pakMigrateLine:pakMigrateLines){
            PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(pakMigrateLine.getAssets());
            pakAssets.setOrg(pakMigrate.getUorg());
            pakAssets.setDept(pakMigrate.getUdept());
            pakAssets.setUser(pakMigrate.getUuser());
            pakAssets.setStatus(AssetsType.DIVERT.getCode());
            pakAssetsMapper.updateByPrimaryKeySelective(pakAssets);
        }
    }

    @Override
    public void transfer(PakTransfer pakTransfer) {
        List<PakTransferLine> pakTransferLines = pakTransferLineMapper.findByTransfer(pakTransfer.getId());
        for(PakTransferLine pakTransferLine:pakTransferLines){
            PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(pakTransferLine.getAssets());
            pakAssets.setOrg(pakTransfer.getIorg());
            pakAssets.setDept(pakTransfer.getIdept());
            pakAssets.setLocation(pakTransfer.getIlocation());
            pakAssets.setStatus(AssetsType.TRANS.getCode());
            pakAssetsMapper.updateByPrimaryKeySelective(pakAssets);
        }
    }

    @Override
    public boolean inventory(PakInventory inventory) {
        List<PakAssets> pakAssetses = pakAssetsMapper.findByCondition(inventory);
        if(pakAssetses.size()==0){
            return false;
        }
        for(PakAssets pakAssets:pakAssetses){
            PakInventoryLine line = new PakInventoryLine();
            line.setInventory(inventory.getId());
            line.setAssets(pakAssets.getId());
            line.setUser(inventory.getUser());
            line.setStatus(1);
            pakInventoryLineMapper.insert(line);
        }
        return true;
    }

    @Override
    public int inventoryNum(PakInventory inventory) {
        return  pakAssetsMapper.findByCondition(inventory).size();
    }

    @Override
    public void requisition(PakRequisition requisition) {
        List<PakRequisitionLine> pakRequisitionLines = pakRequisitionLineMapper.findByRequisitonId(requisition.getId());
        for(PakRequisitionLine pakRequisitionLine:pakRequisitionLines){
            PakAssets pakAssets = pakAssetsMapper.selectByPrimaryKey(pakRequisitionLine.getAssets());
            pakAssets.setOrg(requisition.getOrg());
            pakAssets.setDept(requisition.getDept());
            pakAssets.setUser(requisition.getUser());
            pakAssets.setStatus(1);
            pakAssetsMapper.updateByPrimaryKeySelective(pakAssets);
        }
    }


    @Override
    public List<Map<String, String>> convMapData(List<Map<String, String>> list) {
        for(Map<String,String> map:list){
            map.put("dept", String.valueOf(sysDeptMapper.findIdByName(map.get("deptName"))));
            map.put("org", String.valueOf(sysOrgMapper.findIdByName(map.get("orgName"))));
            map.put("location", String.valueOf(pakLocationMapper.findIdByName(map.get("locationName"))));
            map.put("user", String.valueOf(sysUserMapper.findIdByName(map.get("userName"))));
            map.put("categories", String.valueOf(pakAssetsClassMapper.findIdByName(map.get("categoriesName"))));
            map.put("status", String.valueOf(AssetsType.getCodeByMsg(map.get("status"))));
            map.put("manager", String.valueOf(sysUserMapper.findIdByName(map.get("manager"))));
            map.put("stockWay",String.valueOf(PurWay.getCodeByMsg(map.get("stockWay"))));
        }
        return list;
    }

    @Override
    public Assets findByCode(String code) {
        PakAssets pakAssets = pakAssetsMapper.findByCode(code);
        return pakAssets!=null?new Assets(pakAssets):null;
    }

    @Override
    public List<Map> groupStatus(Long id) {
        return pakAssetsMapper.groupByStatus(id);
    }


}
